//用户数据模块

import { checkLoginReq, getUserInfoReq } from '@/api/user'


// 解构ajax接口函数


const state = {
    token: localStorage.getItem('t_k'),
    role: localStorage.getItem('role'),
    userInfo: {}, //用户信息

}
const getters = {
}
const mutations = {
    SET_TOKEN(state, data) {
        state.token = data
        localStorage.setItem('t_k', data)
    },
    SET_ROLE(state, data) {
        state.role = data
        localStorage.setItem('role', data)
    },
    SET_USERINFO(state, data) {
        state.userInfo = data

    },
    CLEAR(state) {
        //清空vuex
        state.userInfo = {}
        state.token = ''
        state.role = ''

        //清空本地
        localStorage.clear()
    },

}
const actions = {
    A_login({ commit }, data) {
        return new Promise(async resolve => {
            let res = await checkLoginReq(data)
            let { code, msg, token, role } = res.data
            if (code === 0) {
                commit('SET_TOKEN', 'Bearer ' + token)
                commit('SET_ROLE', role)
                resolve()
            }
        }

        )
    },

    // //获取用户信息
    //获取用户信息
    A_getUserInfo({ commit }) {
        return new Promise(async (resolve,reject) => {
            // //发送请求
            // let res = await getUserInfoReq()
            // //调用mutations里面的同步方法 存储数据到vuex中
            // commit('SET_USERINFO', res.data)
            getUserInfoReq()
            .then(res => {
              commit('SET_USERINFO', res.data)
              resolve()
            })
            .catch(err => {
              reject(err)
            })
        })
    },

    //清空数据
    A_clear({ commit }) {
        return new Promise(resolve => {
            commit('CLEAR')
            resolve()
        })
    },
}


export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions,
} 